﻿using AGooday.AgChat.Api.Data;
using AGooday.AgChat.Api.Models;
using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace AGooday.AgChat.Api.Controllers
{// Controllers/GroupsController.cs
    [ApiController]
    [Route("api/[controller]")]
    [Authorize]
    public class GroupsController : ControllerBase
    {
        private readonly ApplicationDbContext _context;

        public GroupsController(ApplicationDbContext context)
        {
            _context = context;
        }

        [HttpGet]
        public async Task<IActionResult> GetGroups()
        {
            var userId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

            var groups = await _context.GroupMembers
                .Where(gm => gm.UserId == userId)
                .Include(gm => gm.Group)
                .ThenInclude(g => g.Members)
                .ThenInclude(m => m.User)
                .Select(gm => new
                {
                    gm.Group.Id,
                    gm.Group.Name,
                    gm.Group.Description,
                    gm.Group.Avatar,
                    gm.Role,
                    Members = gm.Group.Members.Select(m => new
                    {
                        m.User.Id,
                        m.User.Username,
                        m.User.Avatar,
                        m.Role
                    }),
                    UnreadCount = _context.Messages.Count(m =>
                        m.GroupId == gm.GroupId && m.SenderId != userId && !m.IsRead)
                })
                .ToListAsync();

            return Ok(groups);
        }

        [HttpPost]
        public async Task<IActionResult> CreateGroup([FromBody] CreateGroupRequest request)
        {
            var userId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

            var group = new Group
            {
                Name = request.Name,
                Description = request.Description,
                Avatar = string.IsNullOrEmpty(request.Avatar) ?
                    $"https://ui-avatars.com/api/?name={request.Name}&background=random" : request.Avatar,
                CreatorId = userId,
                CreatedAt = DateTime.UtcNow
            };

            _context.Groups.Add(group);
            await _context.SaveChangesAsync();

            // Add creator as admin
            var groupMember = new GroupMember
            {
                GroupId = group.Id,
                UserId = userId,
                Role = "admin",
                JoinedAt = DateTime.UtcNow
            };

            _context.GroupMembers.Add(groupMember);

            // Add other members
            foreach (var memberId in request.MemberIds)
            {
                if (memberId != userId)
                {
                    _context.GroupMembers.Add(new GroupMember
                    {
                        GroupId = group.Id,
                        UserId = memberId,
                        Role = "member",
                        JoinedAt = DateTime.UtcNow
                    });
                }
            }

            await _context.SaveChangesAsync();

            return Ok(group);
        }

        [HttpPost("{groupId}/members")]
        public async Task<IActionResult> AddMember(int groupId, [FromBody] int memberId)
        {
            var userId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

            // Check if user is admin of the group
            var isAdmin = await _context.GroupMembers
                .AnyAsync(gm => gm.GroupId == groupId && gm.UserId == userId && gm.Role == "admin");

            if (!isAdmin)
            {
                return Forbid("Only admins can add members");
            }

            // Check if member already in group
            var existingMember = await _context.GroupMembers
                .FirstOrDefaultAsync(gm => gm.GroupId == groupId && gm.UserId == memberId);

            if (existingMember != null)
            {
                return BadRequest("User already in group");
            }

            var groupMember = new GroupMember
            {
                GroupId = groupId,
                UserId = memberId,
                Role = "member",
                JoinedAt = DateTime.UtcNow
            };

            _context.GroupMembers.Add(groupMember);
            await _context.SaveChangesAsync();

            return Ok("Member added");
        }

        [HttpDelete("{groupId}/members/{memberId}")]
        public async Task<IActionResult> RemoveMember(int groupId, int memberId)
        {
            var userId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

            // Check if user is admin of the group or removing themselves
            var isAdmin = await _context.GroupMembers
                .AnyAsync(gm => gm.GroupId == groupId && gm.UserId == userId && gm.Role == "admin");

            if (!isAdmin && userId != memberId)
            {
                return Forbid("Only admins can remove members");
            }

            var groupMember = await _context.GroupMembers
                .FirstOrDefaultAsync(gm => gm.GroupId == groupId && gm.UserId == memberId);

            if (groupMember == null)
            {
                return NotFound("Member not found");
            }

            _context.GroupMembers.Remove(groupMember);
            await _context.SaveChangesAsync();

            return Ok("Member removed");
        }
    }

    public class CreateGroupRequest
    {
        public string Name { get; set; }
        public string Description { get; set; }
        public string Avatar { get; set; }
        public List<int> MemberIds { get; set; } = new List<int>();
    }
}
